<template>
  <el-dialog
    title="选择客户"
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    width="700px"
    top="10vh"
    destroy-on-close
  >
    <div class="customer-select">
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="输入客户姓名/手机号搜索"
          prefix-icon="fa fa-search"
          clearable
          @keyup.enter="searchCustomers"
        >
          <template #append>
            <el-button @click="searchCustomers">搜索</el-button>
          </template>
        </el-input>
      </div>
      
      <div class="customers-table">
        <el-table
          :data="customers"
          stripe
          border
          height="350px"
          v-loading="loading"
          @row-click="handleRowClick"
          highlight-current-row
        >
          <el-table-column label="客户姓名" prop="name" width="120"></el-table-column>
          <el-table-column label="手机号" prop="phone" width="130"></el-table-column>
          <el-table-column label="会员等级" width="120">
            <template #default="scope">
              <el-tag :type="getLevelType(scope.row.level)">
                {{ scope.row.level }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="折扣" width="100">
            <template #default="scope">
              {{ scope.row.discount }}%
            </template>
          </el-table-column>
          <el-table-column label="积分" prop="points" width="100" align="right"></el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click.stop="selectCustomer(scope.row)"
              >
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="dialog-footer">
        <el-button @click="$emit('update:modelValue', false)">取消</el-button>
        <el-button type="primary" @click="createNewCustomer">
          <i class="fa fa-plus"></i> 新建客户
        </el-button>
      </div>
    </div>
    
    <!-- 新建客户对话框 -->
    <el-dialog
      v-model="newCustomerVisible"
      title="新建客户"
      width="500px"
      append-to-body
      destroy-on-close
    >
      <el-form
        :model="newCustomerForm"
        :rules="formRules"
        ref="newCustomerFormRef"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="newCustomerForm.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="newCustomerForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="会员等级" prop="level">
          <el-select v-model="newCustomerForm.level" placeholder="选择会员等级">
            <el-option
              v-for="level in memberLevels"
              :key="level.value"
              :label="level.label"
              :value="level.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="折扣" prop="discount">
          <el-input-number
            v-model="newCustomerForm.discount"
            :min="0"
            :max="100"
            :step="5"
          ></el-input-number>
          <span class="discount-unit">%</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="newCustomerVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNewCustomer">保存</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

// 模拟客户数据
const mockCustomers = [
  {
    id: 1,
    name: '张三',
    phone: '13800138001',
    level: '钻石会员',
    discount: 20,
    points: 5280
  },
  {
    id: 2,
    name: '李四',
    phone: '13900139002',
    level: '金卡会员',
    discount: 15,
    points: 3650
  },
  {
    id: 3,
    name: '王五',
    phone: '13700137003',
    level: '银卡会员',
    discount: 10,
    points: 1280
  },
  {
    id: 4,
    name: '赵六',
    phone: '13600136004',
    level: '普通会员',
    discount: 5,
    points: 520
  },
  {
    id: 5,
    name: '孙七',
    phone: '13500135005',
    level: '至尊会员',
    discount: 25,
    points: 10800
  }
]

interface CustomerForm {
  name: string;
  phone: string;
  level: string;
  discount: number;
}

export default defineComponent({
  name: 'CustomerSelectDialog',
  props: {
    modelValue: {
      type: Boolean,
      required: true
    }
  },
  emits: ['update:modelValue', 'select-customer'],
  setup(props, { emit }) {
    // 状态变量
    const loading = ref(false)
    const searchQuery = ref('')
    const customers = ref(mockCustomers)
    const newCustomerVisible = ref(false)
    const newCustomerFormRef = ref<FormInstance | null>(null)
    
    // 会员等级选项
    const memberLevels = [
      { value: '普通会员', label: '普通会员' },
      { value: '银卡会员', label: '银卡会员' },
      { value: '金卡会员', label: '金卡会员' },
      { value: '钻石会员', label: '钻石会员' },
      { value: '至尊会员', label: '至尊会员' }
    ]
    
    // 新建客户表单
    const newCustomerForm = ref<CustomerForm>({
      name: '',
      phone: '',
      level: '普通会员',
      discount: 5
    })
    
    // 表单验证规则
    const formRules = ref<FormRules>({
      name: [
        { required: true, message: '请输入客户姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      level: [
        { required: true, message: '请选择会员等级', trigger: 'change' }
      ]
    })
    
    // 获取会员等级样式类型
    const getLevelType = (level: string) => {
      const typeMap: Record<string, 'success' | 'warning' | 'info' | 'primary' | 'danger'> = {
        '普通会员': 'info',
        '银卡会员': 'info',
        '金卡会员': 'warning',
        '钻石会员': 'primary',
        '至尊会员': 'success'
      }
      
      return typeMap[level] || 'info'
    }
    
    // 搜索客户
    const searchCustomers = () => {
      loading.value = true
      
      // 模拟API请求延迟
      setTimeout(() => {
        if (searchQuery.value) {
          const query = searchQuery.value.toLowerCase()
          customers.value = mockCustomers.filter(
            customer => 
              customer.name.toLowerCase().includes(query) || 
              customer.phone.includes(query)
          )
        } else {
          customers.value = mockCustomers
        }
        
        loading.value = false
      }, 300)
    }
    
    // 处理行点击事件
    const handleRowClick = (row: any) => {
      selectCustomer(row)
    }
    
    // 选择客户
    const selectCustomer = (customer: any) => {
      emit('select-customer', customer)
      emit('update:modelValue', false)
    }
    
    // 新建客户
    const createNewCustomer = () => {
      newCustomerForm.value = {
        name: '',
        phone: '',
        level: '普通会员',
        discount: 5
      }
      newCustomerVisible.value = true
    }
    
    // 保存新客户
    const saveNewCustomer = async () => {
      if (!newCustomerFormRef.value) return
      
      await newCustomerFormRef.value.validate((valid, fields) => {
        if (valid) {
          // 模拟保存客户
          const newCustomer = {
            id: Date.now(),
            name: newCustomerForm.value.name,
            phone: newCustomerForm.value.phone,
            level: newCustomerForm.value.level,
            discount: newCustomerForm.value.discount,
            points: 0
          }
          
          // 实际应用中应该调用API保存客户
          mockCustomers.push(newCustomer)
          customers.value = [...mockCustomers]
          
          ElMessage.success('客户创建成功')
          newCustomerVisible.value = false
          
          // 自动选择新创建的客户
          selectCustomer(newCustomer)
        }
      })
    }
    
    // 组件挂载时加载客户列表
    onMounted(() => {
      loading.value = true
      
      // 模拟API请求
      setTimeout(() => {
        // 实际应用中从后端加载客户数据
        loading.value = false
      }, 500)
    })
    
    return {
      loading,
      searchQuery,
      customers,
      newCustomerVisible,
      newCustomerFormRef,
      memberLevels,
      newCustomerForm,
      formRules,
      getLevelType,
      searchCustomers,
      handleRowClick,
      selectCustomer,
      createNewCustomer,
      saveNewCustomer
    }
  }
})
</script>

<style scoped lang="scss">
.customer-select {
  .search-section {
    margin-bottom: 20px;
  }
  
  .customers-table {
    margin-bottom: 20px;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: space-between;
    padding-top: 10px;
  }
}

.discount-unit {
  margin-left: 5px;
  color: #606266;
}
</style> 